// AI服务工厂类
const aiConfig = require('../../config/ai.config');
const AIServiceBase = require('./AIServiceBase');

class AIServiceFactory {
  constructor() {
    this.services = new Map();
    this.initialized = false;
    this.commonConfig = aiConfig.common;
  }
  
  /**
   * 初始化所有AI服务
   */
  async initialize() {
    if (this.initialized) return;
    
    try {
      // 动态加载所有AI服务适配器
      const providers = Object.keys(aiConfig.providers);
      
      for (const provider of providers) {
        if (aiConfig.providers[provider].enabled) {
          try {
            const ServiceClass = require(`./${provider.charAt(0).toUpperCase() + provider.slice(1)}Service`);
            const service = new ServiceClass(aiConfig.providers[provider]);
            this.services.set(provider, service);
            console.log(`[AI Factory] ${provider} service initialized`);
          } catch (error) {
            console.warn(`[AI Factory] Failed to initialize ${provider} service:`, error.message);
          }
        }
      }
      
      this.initialized = true;
      console.log(`[AI Factory] Initialized ${this.services.size} AI services`);
    } catch (error) {
      console.error('[AI Factory] Initialization failed:', error);
      throw error;
    }
  }
  
  /**
   * 获取指定的AI服务
   * @param {string} provider - 服务提供商名称
   * @returns {AIServiceBase} AI服务实例
   */
  getService(provider) {
    if (!this.initialized) {
      throw new Error('AI services not initialized. Call initialize() first.');
    }
    
    const service = this.services.get(provider);
    if (!service) {
      throw new Error(`AI service '${provider}' not found or not enabled`);
    }
    
    return service;
  }
  
  /**
   * 获取默认的AI服务
   * @returns {AIServiceBase} 默认AI服务实例
   */
  getDefaultService() {
    return this.getService(aiConfig.defaultProvider);
  }
  
  /**
   * 获取所有可用的AI服务信息
   * @returns {Array} 服务信息数组
   */
  getAllServicesInfo() {
    const servicesInfo = [];
    for (const [name, service] of this.services) {
      servicesInfo.push(service.getInfo());
    }
    return servicesInfo;
  }
  
  /**
   * 智能选择最佳AI服务
   * @returns {AIServiceBase} 最佳AI服务实例
   */
  async getBestService() {
    // 首先尝试默认服务
    try {
      const defaultService = this.getDefaultService();
      if (await defaultService.isAvailable()) {
        return defaultService;
      }
    } catch (error) {
      console.warn(`[AI Factory] Default service ${aiConfig.defaultProvider} not available:`, error.message);
    }
    
    // 尝试其他可用服务
    for (const [name, service] of this.services) {
      if (name !== aiConfig.defaultProvider) {
        try {
          if (await service.isAvailable()) {
            console.log(`[AI Factory] Using fallback service: ${name}`);
            return service;
          }
        } catch (error) {
          console.warn(`[AI Factory] Service ${name} not available:`, error.message);
        }
      }
    }
    
    throw new Error('No available AI services');
  }
  
  /**
   * 发送聊天消息（自动选择最佳服务）
   * @param {Array} messages - 消息数组
   * @param {Object} options - 额外选项
   * @param {string} provider - 指定服务提供商（可选）
   * @returns {Promise<Object>} AI响应
   */
  async chat(messages, options = {}, provider = null) {
    const service = provider ? this.getService(provider) : await this.getBestService();
    return await service.chat(messages, { ...this.commonConfig, ...options });
  }
  
  /**
   * 生成文本（自动选择最佳服务）
   * @param {string} prompt - 提示文本
   * @param {Object} options - 额外选项
   * @param {string} provider - 指定服务提供商（可选）
   * @returns {Promise<string>} 生成的文本
   */
  async generateText(prompt, options = {}, provider = null) {
    const service = provider ? this.getService(provider) : await this.getBestService();
    return await service.generateText(prompt, { ...this.commonConfig, ...options });
  }
  
  /**
   * 检查服务健康状态
   * @returns {Promise<Object>} 健康状态信息
   */
  async getHealthStatus() {
    const status = {
      initialized: this.initialized,
      defaultProvider: aiConfig.defaultProvider,
      services: {},
      availableCount: 0,
      totalCount: this.services.size
    };
    
    for (const [name, service] of this.services) {
      try {
        const isAvailable = await service.isAvailable();
        status.services[name] = {
          ...service.getInfo(),
          available: isAvailable
        };
        
        if (isAvailable) {
          status.availableCount++;
        }
      } catch (error) {
        status.services[name] = {
          ...service.getInfo(),
          available: false,
          error: error.message
        };
      }
    }
    
    return status;
  }
}

// 创建单例实例
const aiServiceFactory = new AIServiceFactory();

module.exports = aiServiceFactory;